# _*_ coding:utf-8 _*_
# @Time  : 2023.06.28
# @Author: zizlee
import pathlib
from fastapi import APIRouter, UploadFile, Form, Header, Query
from v1_all_api.all_response import AllResponse
from hutool import security
from db import FAConnection
from v1_all_api.all_utils import file_utils, datetime_utils
from v1_all_api.constant import WORK_FILE_TYPES
from configs import FILE_STORAGE, STATIC_FILE_HOST


work_file_api = APIRouter()


@work_file_api.post('/upload/')  # 上传工作文件
async def create_work_file(ruizy_token: str = Header(...), file: UploadFile = Form(...),
                           file_type: int = Form(...), file_date: str = Form(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    file_date = datetime_utils.auth_datetime_string(file_date, f='%Y-%m-%d')
    if not file_date:
        return AllResponse.validate_error(msg='文件日期格式不正确!')
    # 查看后缀
    if pathlib.Path(file.filename).suffix != '.docx':
        return AllResponse.validate_error(msg='文件格式不正确！请使用docx格式')
    save_path, sql_path = file_utils.get_file_paths(module_name='WorkFile', filename=file.filename,
                                                    hashed=True, date_folder=file_date[0:7].replace('-', ''))
    # 保存附件到指定文件夹
    file_content = await file.read()
    with open(save_path, 'wb') as fp:
        fp.write(file_content)
    await file.close()
    # 保存到数据库
    with FAConnection() as cursor:
        cursor.execute("SELECT id,file_url FROM work_file WHERE file_date=%s AND file_type=%s LIMIT 1;", [file_date, file_type])
        exist_obj = cursor.fetchone()
        if exist_obj:
            # 更新
            c = cursor.execute('UPDATE work_file SET name=%s,user_id=%s,file_url=%s WHERE id=%s LIMIT 1;',
                               [file.filename, person['uid'], sql_path, exist_obj['id']])
            # 删除原来的文件
            if c:
                old_file = pathlib.Path(FILE_STORAGE).joinpath(exist_obj['file_url'])
                if old_file.exists() and old_file.is_file():
                    old_file.unlink()
        else:
            # 加入
            cursor.execute("INSERT INTO work_file (name,user_id,file_date,file_type,file_url) VALUES (%s,%s,%s,%s,%s);",
                           [file.filename, person['uid'], file_date, file_type, sql_path])
    return AllResponse.operate_successfully(msg='上传{}文件成功'.format(WORK_FILE_TYPES.get(file_type, '未知类型')))


@work_file_api.get('/')  # 查询文件列表
def get_work_file_list(ruizy_token: str = Header(...), page: int = Query(1), page_size: int = Query(15),
                       file_type: int = Query(None), file_date: str = Query(None)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    if not file_type:
        return AllResponse.validate_error(msg='类型错误')
    if file_date:
        file_date = datetime_utils.auth_datetime_string(file_date, '%Y-%m-%d')
    db_conn = FAConnection()
    if file_date:
        ret = db_conn.query_paginator(sql='SELECT id,name,user_id,file_date,file_type,file_url FROM work_file WHERE is_active=1 AND file_type=%s AND file_date=%s;',
                                      param=[file_type, file_date], page=page, page_size=page_size)
    else:
        ret = db_conn.query_paginator(sql='SELECT id,name,user_id,file_date,file_type,file_url FROM work_file WHERE is_active=1 AND file_type=%s ORDER BY file_date DESC;',
                                      param=[file_type], page=page, page_size=page_size)
    for rec in ret['data']:
        rec['file_addr'] = STATIC_FILE_HOST + rec['file_url']
    return AllResponse.operate_successfully(data=ret)

